package com.lzy.cloud.payment.utils;

import java.io.*;

public class FileUtil {

    public static byte[] readFile(String path) {

        File file = new File(path);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream((int) file.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024, count = 0;
            byte[] buffer = new byte[buf_size];
            while (-1 != (count = in.read(buffer, 0, buf_size))) {
                byteStream.write(buffer, 0, count);
            }
            return byteStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                byteStream.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String readString(String file) {
        String path = Thread.currentThread().getContextClassLoader().getResource(file).getPath();
        byte[] buffer = readFile(path);
        if (buffer != null)
            return buffer.toString();
        return null;
    }

    /**
     * 本方法可以获取jar包中的资源文件
     *
     * @param file
     * @return
     */
    public String getResources(String file) {
        InputStream is = null;
        try {
            //返回读取指定资源的输入流
            is = this.getClass().getResourceAsStream(file);
            //InputStream is=当前类.class.getResourceAsStream("XX.config");
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String s = "";
            while ((s = br.readLine()) != null)
                return s;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
